package Logging;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;

public class LoggingService {
	private ArrayList<Thread> listaThreaduri=new ArrayList<Thread>();
	
	private int maxServerThreads=1;
	private int minServerThreads=2;
	private Hashtable<Message.MessageImportance, ArrayList<Message>> messageBuffer; 
	private Hashtable<Message.MessageImportance, Integer> messageCount;
	
	public Hashtable<Message.MessageImportance, ArrayList<Message>> getMessageBuffer() {
		return messageBuffer;
	}

	public LoggingService()
	{
		messageBuffer=new Hashtable<Message.MessageImportance, ArrayList<Message>>();
		messageCount=new Hashtable<Message.MessageImportance, Integer>();
		for (Message.MessageImportance mi : Message.MessageImportance.values())
		{
			messageCount.put(mi, new Integer(0));
			messageBuffer.put(mi, new ArrayList<Message>());
		}
	}
	
	public void readConfiguration() {

		try {
			FileInputStream fstream = new FileInputStream("config.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				String name;
				int value=0;
				
				int equalsPos=strLine.indexOf("=");
				name=strLine.substring(0, equalsPos);
				try {
					value=Integer.parseInt(strLine.substring(equalsPos+1));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				
				if(name.equals("minServerThreads"))
					minServerThreads=value;
				else if(name.equals("maxServerThreads"))
					maxServerThreads=value;
				
			}
			in.close();
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}

	}

	public synchronized void sendMessage(Message message)
	{
		messageBuffer.get(message.getMessageImportance()).add(message);
		
		int nr=messageCount.get(message.getMessageImportance());
		
		messageCount.put(message.getMessageImportance(), nr+1);
	//	System.out.println("["+message.getMessageImportance()+"]("+message.getMessageImportance().getPriority()+") "+message.getText());
	}
	
	public static void main(String argv[]) {
		LoggingService loggingService=new LoggingService();
		Client client=new Client("app1","chat",loggingService);
		Server server=new Server(loggingService);
		Thread clientThread=new Thread(client);
		Thread serverThread=new Thread(server);
		clientThread.start();
		serverThread.start();
	}

}
